package com.vvv.shortlink.project.config;


import groovyjarjarantlr4.v4.runtime.misc.NotNull;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.LongAdder;

/**
 * @author vvv
 * @date 2023-12-03 15 30
 * discription
 */
@Configuration
public class ThreadPoolConfig {

    @Bean
    public ThreadPoolExecutor monitorStatsThreadPoolExecutor() {
        // io密集型线程池配置：线程数 = 核数 + 期望cpu利用率 + 1 / cpu计算时间
        int numOfCores = Runtime.getRuntime().availableProcessors();
        int numCoreThread = numOfCores * 10;
        return new ThreadPoolExecutor(
                numCoreThread,
                numCoreThread + 1,
                10,
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(20),
                new ThreadFactory() {
                    private LongAdder longAdder = new LongAdder();
                    @Override
                    public Thread newThread(@NotNull Runnable r) {
                        Thread thread = new Thread(r);
                        thread.setName("短链监控线程" + longAdder.intValue());
                        longAdder.increment();
                        return thread;
                    }
                }
        );
    }
}
